import React, { Component } from 'react';
import { Modal, Form, Button, Input, message } from 'antd';
import { randomNum } from '@/utils/random';
import utils from '@/utils/utils'
import * as ACTIONS from './actions'
import './index.less';
import jsonp from 'jsonp';
import md5 from 'js-md5';

class LoginFn extends Component {
  constructor(props) {
    super(props)
    this.state = {
      collapsed: false,
      sidebar: [],
      // checkNumUrl: 'https://cloud.jss.com.cn:443/clouduser/allow/check.do',
      checkNumUrl: '',
      submited: false,
      tab: 'user',
      dlgTipTxt: '发送验证码',
      msgYzmdis: false,
      seconds: 59,
    }
    this.getMsgCode = this.getMsgCode.bind(this);
    this.onRegister = this.onRegister.bind(this);
    this.onChangepas = this.onChangepas.bind(this);

  }

  componentWillReceiveProps(Props) {
    if (Props.showLogin !== this.props.showLogin) {
      this.updateCheck()//退出更新验证码 
    }
  }


  updateCheck = (e) => {
      //                                        不要这样用， 减少全局变量。 存在一个js文件中，使用时导入
    this.setState({
      checkNumUrl: '//' + window.location.host + window.baseURL + '/login/check.do?_=' + randomNum(32) + Date.parse(new Date())
    })
  }

  handleCancel = (e) => {
    this.props.closeLogin(false);
  }

  getMsgCode() {
    this.props.form.validateFields(['mobile', 'imgyzm'], { force: true }, (err, val) => {
      if (!err) {
        this.countDown()
      }
    })
  }

  countDown() {
    let siv = setInterval(() => {
      this.setState((preState) => ({
        seconds: preState.seconds - 1,
        dlgTipTxt: `${preState.seconds - 1}S后重新发送`,
        msgYzmdis: true
      }), () => {
        if (this.state.seconds === 0) {
          clearInterval(siv);
          this.setState({
            dlgTipTxt: "重新发送",
            seconds: 59,
            msgYzmdis: false
          })
        }
      });
    }, 1000)
  }

  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        this.loginIn(values)
      }
    });
  }

  loginIn(values) {

    this.setState({
      submited: true
    })

    const userLogin = {
      account: values.userName,
      password: md5(values.password),
      randNum: values.yzm,
    }

    const mobileLogin = {
      account: values.mobile,
      password: md5(values.imgyzm || ""),
      randNum: values.msgyzm,
    }

    const datas = this.state.tab === 'mobile' ? mobileLogin : userLogin
    let resfunc = "", ids = "";
    this.$ajax.get('/login/login.do', { params: datas })
      .then(res => {
        this.setState({
          submited: false
        });
        if (res.code === 200) {
          resfunc = res.data.resfunc;
          ids = res.data.id;

          jsonp('//u.jss.com.cn/u/v1/auth/check_login?resfunc=' + resfunc + '&id=' + ids,
            { param: "callback", name: "user_lbn_jsonpResponse" }, (err, res) => {
              if (!err && res.data) {
                let token = res.data.token;
                this.$ajax.get('login/sso.do', { params: { token: token } }).then(res => {
                  this.setState({
                    submited: false
                  });
                  if (res.code === 200) {
                    const data = res.data;
                    let userInfo = data && {
                      cPhone: data.mobile,
                      cUsername: data.userName,
                      cUsertype: data.registertype,
                      taxnum: data.taxnum,
                    }
                    utils.setCookie('adminUser', userInfo)
                    this.props.store.dispatch(ACTIONS.toggleLogin({ isLogin: true }))
                    
                    this.props.closeLogin(false);
                  }else if(res.code === 406){
                    const data = res.data;
                    let userInfo = data && {
                      cPhone: data.mobile,
                      cUsername: data.userName,
                      cUsertype: data.registertype,
                      taxnum: data.taxnum,
                    }
                    
                    utils.setCookie('adminUser', userInfo)
                    // this.props.store.dispatch(ACTIONS.toggleLogin({ isLogin: true }))
                    // this.props.store.dispatch(ACTIONS.isTimeout(true))
                    this.props.closeLogin(false);
                  }else {
                    this.updateCheck();
                  }
                }).catch(error => {
                  this.updateCheck();
                  this.setState({
                    submited: false
                  });
                  message.error('请求登录失败！');
                  throw (error)
                })
              }
            })
        }else{
          this.updateCheck();
          this.setState({
            submited: false
          });
          if(res.code === 403){
            message.warning('用户名或密码错误!');
          }
        }
      })
      .catch(error => {
        this.updateCheck();
        this.setState({
          submited: false
        });
        message.error('请求登录失败！');
        throw (error)
      })
  }

  onRegister() {
    this.props.closeLogin(false, 'register');
  }

  onChangepas() {

    //跳转到用户中心
    window.open("https://u.jss.com.cn/Contents/usercenter/allow/retrieve/retrieve.jsp?redirecturl=bmjc")

    //自己的修改密码页面
    // this.props.closeLogin(false,'changepas');
  }

  // <span className={`tab-item pointer ${this.state.tab === 'user' ? 'active' : ''} `} onClick={() => (this.setState({ tab: 'user', submited: false }))}>账号密码登录</span>
  // <span className={`tab-item pointer ${this.state.tab === 'mobile' ? 'active' : ''} `} onClick={() => (this.setState({ tab: 'mobile', submited: false }))}>手机验证登录</span>
  render() {
    const { getFieldDecorator } = this.props.form;
    const { showLogin } = this.props;

    return (
      <div>
        <Modal
          width='640px'
          maskClosable={false}
          visible={showLogin}
          onCancel={this.handleCancel}
          footer={null}
          destroyOnClose={true}
        >
          <div className="login-container">
            <div className="form-area">
              <div className='tab'>
                <span className={`tab-item pointer ${this.state.tab === 'user' ? 'active' : ''} `} onClick={() => (this.setState({ tab: 'user', submited: false }))}>账号密码登录</span>
              </div>
              {
                this.state.tab === 'user' &&

                <Form>
                  <Form.Item 
                  onSubmit={this.handleSubmit} 
                   className="login-form">
                    {getFieldDecorator('userName', {
                      rules: [{ required: true, message: '请输入账号' }],
                    })(
                      <Input size="large" autoComplete="off" autoCapitalize="off" autoCorrect="off" spellCheck="false" type="text" placeholder="手机号/邮箱/用户名/企业税号" />
                    )}
                  </Form.Item>
                  <Form.Item onSubmit={this.handleSubmit} 
                   className="login-form">
                    {getFieldDecorator('password', {
                      rules: [{ required: true, message: '请输入密码' }],
                    })(
                      <Input size="large" autoComplete="off" autoCapitalize="off" autoCorrect="off" spellCheck="false" type="password" placeholder="密码" />
                    )}
                  </Form.Item>
                  <Form.Item onSubmit={this.handleSubmit} 
                   className="login-form login-form_checknum">
                    {getFieldDecorator('yzm', {
                      rules: [{ required: true, message: '请输入验证码' }],
                    })(
                      <Input size="large" type="text" autoComplete="off" autoCapitalize="off" autoCorrect="off" spellCheck="false" placeholder="验证码" />
                    )}
                    <img className="img_code" src={this.state.checkNumUrl} onClick={this.updateCheck} alt='' />
                  </Form.Item>
                  <div className='forgetPwd pointer' onClick={this.onChangepas}>忘记密码？</div>
                  <Form.Item>
                    <Button size="large" disabled={this.state.submited} onClick={this.handleSubmit} type="primary" htmlType="submit" className="login-form-button">立即登录</Button>
                  </Form.Item>
                </Form>

              }
              {
                this.state.tab === 'mobile' &&
                <Form>
                  <Form.Item onSubmit={this.handleSubmit} className="login-form">
                    {getFieldDecorator('mobile', {
                      rules: [{ required: true, message: '请输入手机号码' }, { pattern: /^1[3|4|5|6|7|8|9][0-9]{9}$/, message: '请输入正确的手机号' },],
                    })(
                      <Input size="large" autoComplete="off" autoCapitalize="off" autoCorrect="off" spellCheck="false" type="tel" placeholder="手机号码" />
                    )}
                  </Form.Item>
                  <Form.Item onSubmit={this.handleSubmit} className="login-form login-form_checknum">
                    {getFieldDecorator('imgyzm', {
                      rules: [{ required: true, message: '请输入图片验证码' }],
                    })(
                      <Input size="large" type="text" autoComplete="off" autoCapitalize="off" autoCorrect="off" spellCheck="false" placeholder="图片验证码" />
                    )}
                    <img className="img_code" src={this.state.checkNumUrl} onClick={this.updateCheck} alt='' />
                  </Form.Item>
                  <Form.Item onSubmit={this.handleSubmit} className="login-form login-form_checkmsg">
                    {getFieldDecorator('msgyzm', {
                      rules: [{ required: true, message: '请输入短信验证码' }],
                    })(
                      <Input size="large" autoComplete="off" autoCapitalize="off" autoCorrect="off" spellCheck="false" placeholder="短信验证码" />
                    )}
                    <Button onClick={this.getMsgCode} disabled={this.state.msgYzmdis}>{this.state.dlgTipTxt}</Button>
                  </Form.Item>
                  <div className='forgetPwd pointer' onClick={this.onChangepas}>忘记密码？</div>
                  <Form.Item>
                    <Button size="large" disabled={this.state.submited} onClick={this.handleSubmit} type="primary" htmlType="submit" className="login-form-button">立即登录</Button>
                  </Form.Item>
                </Form>
              }
              <div className="noACc">
                还没有账号? <span className="pointer" onClick={this.onRegister}>立即注册</span>
              </div>
            </div>
            <div className="app-area">
              <img className='nuoyan_qrcode' src='//nnfw.jss.com.cn/86AE3A2D20A547EE9D7F77718B92D44A/banner-bj.jpg' alt="" />
              <div>
                扫码下载诺言APP
              </div>
            </div>
          </div>
        </Modal>
      </div>
    )
  }
}

const Login = Form.create()(LoginFn)

export default Login